import type { ActionFunctionArgs } from '@remix-run/node'
import { LoaderFunction, json } from '@remix-run/node'

import crypto from 'node:crypto'
export const loader = async () => {
  return json({})
}
export const action: LoaderFunction = async ({ request }: ActionFunctionArgs) => {
  if (request.method !== 'POST') {
    throw new Response('This route only supports POST requests', { status: 405 })
  }
  const reqClone = request.clone()
  const rawPayload = await reqClone.text()
  const signature = request.headers.get('X-Shopify-Hmac-SHA256')
  const getHash = crypto.createHmac('sha256', process.env.SHOPIFY_API_SECRET!).update(rawPayload).digest('base64')
  if (signature !== getHash) {
    throw new Response('Signature mismatch', { status: 401 })
  }
  return json({ message: 'Request completed successfully' })
}
